package polygon.cli;

import org.apache.commons.cli.*;
import polygon.cli.command.EjudgeDeployProblemCommand;
import polygon.cli.command.EjudgeDeployContestCommand;
import polygon.cli.command.ArchiveContestCommand;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MikeMirzayanov (mirzayanovmr@gmail.com)
 */
public class Main {
    private static Map<String, Command> commands = new HashMap<String, Command>();

    public static void main(String[] args) {
        Cli cli = new Cli();

        if (args.length == 0) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("pgn [options] command [arg1 arg2 ... argn]", cli.getOptions());
        }

        CommandLineParser parser = new GnuParser();
        try {
            CommandLine line = parser.parse(cli.getOptions(), args, true);

            if (!line.hasOption("login")) {
                cli.setLogin(System.getenv("PGN_LOGIN"));
            } else {
                cli.setLogin(line.getOptionValue("login"));
            }

            if (!line.hasOption("password")) {
                cli.setPassword(System.getenv("PGN_PASSWORD"));
            } else {
                cli.setPassword(line.getOptionValue("password"));
            }
        }
        catch (ParseException e) {
            System.err.println("Command line can't be parsed: " + e.getMessage());
        }

        String command = null;
        int index = 0;
        for (int i = 0; i < args.length; i++) {
            if (args[i].startsWith("-")) {
                i++;
            } else {
                command = args[i];
                index = i;
            }
        }

        if (!commands.containsKey(command)) {
            System.out.println("Can't find such command, available commands are:");
            for (Map.Entry<String, Command> entry : commands.entrySet()) {
                System.out.println("  " + entry.getKey() + "\t-\t" + entry.getValue().getDescription());
            }
        } else {
            Command active = commands.get(command);
            active.setArgs(Arrays.copyOfRange(args, index + 1, args.length));
            active.setCli(cli);
            active.init();
            active.run();
        }
    }

    static {
        commands.put("edp", new EjudgeDeployProblemCommand());
        commands.put("edc", new EjudgeDeployContestCommand());
        commands.put("ac", new ArchiveContestCommand());
    }
}
